package pers.netty.chat.client;


import lombok.extern.slf4j.Slf4j;
import pers.netty.chat.common.Session;
import pers.netty.chat.common.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 李醴茝
 */
@Slf4j
@Service
public class ChatClientHandler extends ChannelInboundHandlerAdapter {

    private AttributeKey<Session> sk = AttributeKey.valueOf("session");

    /**
     * 此方法会在连接到服务器后被调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info(new Date() + "[疯狂创客圈IM] 登录成功");
    }

    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info(msg.toString());
        if (msg != null && msg instanceof ProtoMsg.Message) {
            ProtoMsg.Message pkg = (ProtoMsg.Message) msg;
            // 聊天处理
            ProtoMsg.MessageRequest request = pkg.getMessageRequest();
            log.info("chatMsg{}", "from=" + request.getFrom() + " , to=" + request.getTo() + " , content=" + request.getContent());
        }
    }

    /**
     * 捕捉到异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }


}
